package com.nclg.exam.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.nclg.exam.dto.*;
import com.nclg.exam.entity.LayResponse;
import com.nclg.exam.service.ExamService;
import com.nclg.exam.service.QuestionService;
import com.nclg.exam.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/exam")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private QuestionService questionService;

    /**
     * 查询正在考试的试卷
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/selectExamPaperByPage")
    public JsonResult selectExamPaperByPage(int page, int limit){
        PageInfo<ExamPaperDto> list = examService.selectExamPaperByPage(page,limit);
        LayResponse<ExamPaperDto> layResponse = new LayResponse<>("0", "", list.getTotal(), list.getList());
        return JsonResult.success(layResponse);
    }

    /**
     * 查询考试历史
     * @param dto
     * @return
     */
    @GetMapping("/selectExamFinishedPaperByPage")
    public JsonResult selectExamFinishedPaperByPage(ExamFinishedPaperDto dto){
        PageInfo<PaperHistoryDto> list = examService.selectExamFinishedPaperByPage(dto);
        LayResponse<PaperHistoryDto> layResponse = new LayResponse<>("0", "", list.getTotal(), list.getList());
        return JsonResult.success(layResponse);
    }

    /**
     * 是否提交过试卷
     * @return
     */
    @GetMapping("/selectIsFinished/{pid}/{uid}")
    public JsonResult selectIsFinished(@PathVariable String pid, @PathVariable String uid){
        boolean isTrue = examService.selectIsFinished(Long.valueOf(pid), Long.valueOf(uid));
        if (!isTrue) return JsonResult.failure();
        return JsonResult.success("请勿重复考试");
    }

    @PostMapping("/submitPaper")
    public JsonResult submitPaper(SubmitPaperDto dto){
        ObjectMapper mapper = new ObjectMapper();
        try {

            List<AnswerDto> answers = mapper.readValue(dto.getAnswerList(), new TypeReference<List<AnswerDto>>() {});
            Long pId = dto.getPId();
            Long uId = dto.getUId();

            boolean isTrue = examService.selectIsFinished(pId, uId);
            if (isTrue) return JsonResult.customResult(400, "请勿重复提交试卷", null);

            //查询试卷的问题
            List<ExamQuestionDto> questions = questionService.selectQuestionByPid(pId);
            //总分
            BigDecimal score = BigDecimal.ZERO;
            for (int i = 0; i < questions.size(); i++) {
                //判断answers(i)的id与questions(i)的id是否相等
                if (questions.get(i).getQId() == answers.get(i).getId()) {
                    //判断是否为简答题
                    if (questions.get(i).getQType().equals("3")){
                        break;
                    }
                    //判断用户答案是否与题库中答案一致
                    if (questions.get(i).getQResult().equals(answers.get(i).getAnswer())){
                        answers.get(i).setScore(answers.get(i).getScore().add(questions.get(i).getQScore()));
                        score = score.add(questions.get(i).getQScore());
                    }
                }
            }

            String answerJson = mapper.writeValueAsString(answers);

            boolean isInsertInto = examService.insertUserPaperAndAnswer(pId, uId, score, answerJson);
            if (!isInsertInto) return JsonResult.failure("交卷失败");
            return JsonResult.success("交卷成功");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return JsonResult.failure("交卷失败");
        }
    }
}
